import 'package:flutter/material.dart';
import 'package:flutter_changdian_football/api/api_response.dart';
import 'package:flutter_changdian_football/api/req/court/req_court.dart';
import 'package:flutter_changdian_football/api/req/match/req_match.dart';
import 'package:flutter_changdian_football/routers/app_routes.dart';
import 'package:flutter_changdian_football/utils/custom_constant.dart';
import 'package:flutter_changdian_football/utils/event/custom_event_util.dart';
import 'package:flutter_changdian_football/widget/dialog/operational_results_dialog.dart';
import 'package:flutter_changdian_football/widget/toast/custom_toast.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';

class CreateContestController extends GetxController {

  CreateContestController({
    required this.regionCode,
    required this.clubId
  });

  final String regionCode;

  final String clubId;

  @override
  void onInit() {
    super.onInit();

    getCourtList(regionCode);
  }

  List courtList = [];
  List<String> courtStrList = [];
  int selectCourtIndex = -1;
  String clubHomeCourtName = '';
  String clubHomeCourtId = '';

  changeSelectCourtIndex(p) {
    selectCourtIndex = p;
    clubHomeCourtName = courtStrList[p];
    clubHomeCourtId = '${courtList[p]['courtId']}';
    update();
  }

  // 获取场地
  getCourtList(p) async {
    var resp = await ReqCourt.courtList(p);
    if (resp.status == Status.completed) {
      if (resp.data['code'] == '200') {
        courtList.clear();
        courtStrList.clear();
        selectCourtIndex = -1;

        courtList.addAll(resp.data['data']);
        for (int i = 0; i < courtList.length; i++) {
          courtStrList.add('${courtList[i]['courtName']}');
        }
        update();
      }
    }
  }

  /// 场地费
  List<String> siteFeeList = List.generate(101, (index) => '$index');
  int selectSiteFeeIndex = -1;
  changeSelectSiteFeeIndex(p) {
    selectSiteFeeIndex = p;
    update();
  }

  /// 人数上限
  List<String> maxNumOfPeopleList = List.generate(28, (index) => '${index + 3}');
  int selectMaxNumOfPeopleIndex = -1;
  changeSelectMaxNumOfPeopleIndex(p) {
    selectMaxNumOfPeopleIndex = p;
    update();
  }

  /// 开始时间
  DateTime? beginDate;
  changeBeginDate(p) {
    beginDate = DateTime.parse(p);
    update();
  }

  /// 结束时间
  DateTime? endDate;
  changeEndDate(p) {
    endDate = DateTime.parse(p);
    update();
  }

  List systemPlayList = [
    {
      'key': 'FIVE_PERSON',
      'val': '五人制'
    },
    {
      'key': 'SEVENS',
      'val': '七人制'
    },
    {
      'key': 'EIGHT_PERSON',
      'val': '八人制'
    },
    {
      'key': '十一人制',
      'val': 'ELEVEN_PERSON'
    }
  ];

  List<String> systemPlayStrList = ['五人制', '七人制', '八人制', '十一人制'];
  int selectSystemPlayIndex = -1;
  changeSelectSystemPlayIndex(p) {
    selectSystemPlayIndex = p;
    update();
  }

  /// 是否放水惩罚
  bool isPunishment = true;
  changePunishment() {
    isPunishment = !isPunishment;
    update();
  }

  TextEditingController remarkController = TextEditingController();



  // 球衣颜色
  List<String> jerseyColorList = [
    '红色', '橙色', '黄色', '绿色', '蓝色', '紫色', '灰色', '棕色', '白色', 
    '黑色', '粉红色', '蓝白条纹', '红白条纹', '黑白条纹', '红黑条纹', '黄黑条纹', '其他颜色', '未指定'
  ];
  int selectJerseyColorIndex = 17;
  chaneJerseyColor(p) {
    selectJerseyColorIndex = p;
    update();
  }

  TextEditingController opponentController = TextEditingController();
  String? opponent;
  changeOpponent() {
    opponent = opponentController.text;
    update();
  }

  

  /// 创建比赛
  createMatch() async {
    FocusScope.of(Get.context!).requestFocus(FocusNode());
    if (selectCourtIndex == -1) {
      CustomToast.showTextToast('请选择场地');
      return ;
    }

    if (selectSiteFeeIndex == -1) {
      CustomToast.showTextToast('请选择场地费');
      return ;
    }

    if (selectMaxNumOfPeopleIndex == -1) {
      CustomToast.showTextToast('请选择人数上限');
      return ;
    }
    
    if (beginDate == null) {
      CustomToast.showTextToast('请选择比赛开始时间');
      return ;
    }

    if (endDate == null) {
      CustomToast.showTextToast('请选择比赛结束时间');
      return ;
    }

    if (selectSystemPlayIndex == -1) {
      CustomToast.showTextToast('请选择比赛赛制');
      return ;
    }

    try {
      EasyLoading.show();

      var resp = await ReqMatch.createMatch(
        clubId: clubId,
        courtId: clubHomeCourtId,
        courtName: clubHomeCourtName,
        siteFees: siteFeeList[selectSiteFeeIndex],
        playerLimit: maxNumOfPeopleList[selectMaxNumOfPeopleIndex],
        matchStartTime: beginDate.toString().split('.')[0],
        matchEndTime: endDate.toString().split('.')[0],
        matchRulesName: systemPlayList[selectSystemPlayIndex]['val'],
        matchRulesValue: systemPlayList[selectSystemPlayIndex]['key'],
        isPunishment: isPunishment,
        remark: remarkController.text,
        jerseyColor: jerseyColorList[selectJerseyColorIndex],
        opponent: opponent
      );
      if (resp.status == Status.completed) {
        if (resp.data['code'] == '200') {
          OperationalResultsDialog.show(
            Get.context!,
            text: '创建比赛成功',
            icon: 'assets/images/img_tc_cg.png',
            confirmTap: () {
              Get.until((route) => Get.currentRoute == AppRoutes.main);
              eventBus.fire(const BottomNavigationBarEvent(CustomConstant.EVENT_CLUB_REFRESH));
            }
          );
        } else {
          OperationalResultsDialog.show(
            Get.context!,
            text: resp.data['msg'],
            icon: 'assets/images/img_tc_sb.png',
            confirmTap: () {
              Get.back();
            }
          );
          }
      } else {
        OperationalResultsDialog.show(
          Get.context!,
          text: '创建比赛失败',
          icon: 'assets/images/img_tc_sb.png',
          confirmTap: () {
            Get.back();
          }
        );
      }
    } catch (e) {
      OperationalResultsDialog.show(
        Get.context!,
        text: '创建比赛失败',
        icon: 'assets/images/img_tc_sb.png',
        confirmTap: () {
          Get.back();
        }
      );
    } finally {
      EasyLoading.dismiss();
    }
  }

}